package com.yxr.service.impl;

import com.mysql.cj.x.protobuf.Mysqlx;
import com.yxr.domain.ResponseResult;
import com.yxr.domain.entity.LoginUser;
import com.yxr.domain.entity.User;
import com.yxr.domain.exception.SystemException;
import com.yxr.enums.AppHttpCodeEnum;
import com.yxr.service.LoginService;
import com.yxr.utils.JwtUtil;
import com.yxr.utils.RedisCache;
import com.yxr.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (Objects.isNull(authenticate)){
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }
        LoginUser principal = (LoginUser) authenticate.getPrincipal();

        String id = principal.getUser().getId().toString();

        String jwt = JwtUtil.createJWT(id);

        redisCache.setCacheObject("login:"+id,principal);

        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);


        return ResponseResult.okResult(map);
    }



    @Override
    public ResponseResult loginout() {
        //获取当前登录的用户id
        Long userId = SecurityUtils.getUserId();
        //删除redis中
        redisCache.deleteObject("login:"+userId);
        return ResponseResult.okResult();
    }
}
